package top.jacktgq.cas;
/**
 * 
 * @Title: LockCas.java 
 * @Package top.jacktgq.cas 
 * @Description: 使用cas模拟一个锁
 * @author CandyWall   
 * @date 2020年11月3日 下午5:24:52 
 * @version V1.0
 */

import java.util.concurrent.atomic.AtomicInteger;

import top.jacktgq.utils.LogUtils;
import top.jacktgq.utils.Sleeper;

public class LockCas {
	//0 没加锁
	//1 加锁
	private AtomicInteger state = new AtomicInteger(0);
	
	//加锁
	private void lock() {
		while(true) {
			if(state.compareAndSet(0, 1)) {
				LogUtils.log("LockCas", "lock...");
				break;
			}
		}
	}
	
	//解锁：unlock方法只有锁的持有线程才可以调用到，所以不需要调用compareAndSet()方法
	private void unlock() {
		LogUtils.log("LockCas", "unlock...");
		state.set(0);
	}
	
	public static void main(String[] args) {
		LockCas lock = new LockCas();
		Thread t1 = new Thread(() -> {
			LogUtils.log("LockCas", "begin...");
			lock.lock();
			Sleeper.sleep(1);
			lock.unlock();
		}, "t1");
		Thread t2 = new Thread(() -> {
			LogUtils.log("LockCas", "begin...");
			lock.lock();
			Sleeper.sleep(1);
			lock.unlock();
		}, "t2");
		Thread t3 = new Thread(() -> {
			LogUtils.log("LockCas", "begin...");
			lock.lock();
			Sleeper.sleep(1);
			lock.unlock();
		}, "t3");
		
		t1.start();
		t2.start();
		t3.start();
	}
}
